package com.luolc.instantmessager.login;
/*
 * The MIT License (MIT)
 *
 * Copyright (c) 2016-2017 Luolc
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

import android.app.Activity;
import android.content.Intent;

import com.afollestad.materialdialogs.MaterialDialog;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseCommonUtils;
import com.luolc.instantmessager.R;
import com.luolc.instantmessager.home.HomeActivity;
import com.luolc.instantmessager.util.UiUtils;

import io.reactivex.BackpressureStrategy;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class LoginViewModel {
  public String userId = "";

  public String password = "";

  private final Activity activity;

  private boolean onProgress = false;

  LoginViewModel(Activity activity) {
    this.activity = activity;
  }

  /**
   * Checks whether it is valid to login now.
   *
   * @return {@code true} if valid
   */
  private boolean isValid() {
    return !userId.isEmpty() && !password.isEmpty();
  }

  public void login() {
    if (!EaseCommonUtils.isNetWorkConnected(activity)) {
      UiUtils.toast(activity, "网络连接不可用");
      return;
    }

    if (!isValid()) {
      UiUtils.toast(activity, R.string.login_input_non_empty_message);
      return;
    }

    onProgress = true;
    final MaterialDialog progressDialog = new MaterialDialog.Builder(activity)
        .content("登录中……")
        .progress(true, 0)
        .canceledOnTouchOutside(false)
        .cancelListener(dialog -> onProgress = false)
        .build();
    progressDialog.show();

    Flowable
        .create(
            emitter -> EMClient.getInstance().login(userId, password, new EMCallBack() {
              @Override
              public void onSuccess() {
                emitter.onNext("success");
                emitter.onComplete();
              }

              @Override
              public void onError(int code, String message) {
                emitter.onError(new RuntimeException(message));
              }

              @Override
              public void onProgress(int progress, String status) {
                // ignore
              }
            }),
            BackpressureStrategy.BUFFER)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            result -> {
              EMClient.getInstance().chatManager().loadAllConversations();
              EMClient.getInstance().groupManager().loadAllGroups();
              Intent intent = new Intent(activity, HomeActivity.class);
              if (!activity.isFinishing() && progressDialog.isShowing()) {
                progressDialog.cancel();
              }
              activity.startActivity(intent);
              activity.finish();
            },
            throwable -> {
              if (!onProgress) {
                return;
              }
              UiUtils.toast(activity, "登录失败：" + throwable.getMessage());
              progressDialog.cancel();
            });
  }
}
